package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.base.BaseEntity;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.enums.TxnType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WdyDirectReward;
import com.ruoyi.system.domain.WdyTxnHistory;
import com.ruoyi.system.domain.WdyUser;
import com.ruoyi.system.mapper.WdyDirectRewardMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 直推奖 服务层实现
 * 
 * @author ruoyi
 * @date 2019-12-26
 */
@Service
public class WdyDirectRewardServiceImpl extends ServiceImpl<WdyDirectRewardMapper, WdyDirectReward> implements IWdyDirectRewardService
{

	@Autowired
	private IWdyUserService wdyUserService;
	@Autowired
	private IWdyTxnHistoryService wdyTxnHistoryService;

	@Autowired
	private IWdyBuyProductService wdyBuyProductService;

	@Autowired
	private ISysConfigService sysConfigService;
	/**
     * 查询直推奖信息
     * 
     * @param id 直推奖ID
     * @return 直推奖信息
     */
    @Override
	public WdyDirectReward selectWdyDirectRewardById(Long id)
	{
	    return baseMapper.selectWdyDirectRewardById(id);
	}
	
	/**
     * 查询直推奖列表
     * 
     * @param wdyDirectReward 直推奖信息
     * @return 直推奖集合
     */
	@Override
	public List<WdyDirectReward> selectWdyDirectRewardList(WdyDirectReward wdyDirectReward)
	{
	    return baseMapper.selectWdyDirectRewardList(wdyDirectReward);
	}
	
    /**
     * 新增直推奖
     * 
     * @param wdyDirectReward 直推奖信息
     * @return 结果
     */
	@Override
	public int insertWdyDirectReward(WdyDirectReward wdyDirectReward)
	{
	    return baseMapper.insertWdyDirectReward(wdyDirectReward);
	}
	
	/**
     * 修改直推奖
     * 
     * @param wdyDirectReward 直推奖信息
     * @return 结果
     */
	@Override
	public int updateWdyDirectReward(WdyDirectReward wdyDirectReward)
	{
	    return baseMapper.updateWdyDirectReward(wdyDirectReward);
	}

	/**
     * 删除直推奖对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteWdyDirectRewardByIds(String ids)
	{
		return baseMapper.deleteWdyDirectRewardByIds(Convert.toStrArray(ids));
	}


	@Transactional(rollbackFor = Exception.class)
	@Override
	public void reward(String userId, BigDecimal txnAmount, Long txnId, int type) {
		if(!"1".equals(sysConfigService.selectConfigByKey("directreward_state"))){
			return;
		}

		QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("referrer_id");
		queryWrapper.eq("user_id", userId);
		WdyUser user = wdyUserService.getOne(queryWrapper);
		String referrerId = user.getReferrerId();
		if(StringUtils.isEmpty(referrerId)) {
			return;
		}
		QueryWrapper<WdyUser> referrerQuery = new QueryWrapper<>();
		referrerQuery.select("cnn_withdraw_amount", "version");
		referrerQuery.eq("user_id", referrerId);
		WdyUser referrerUser = wdyUserService.getOne(referrerQuery);

		BigDecimal rechargeRatio = new BigDecimal(sysConfigService.selectConfigByKey("recharge_directreward_ratio"));
		BigDecimal buyProductRatio = new BigDecimal(sysConfigService.selectConfigByKey("buy_product_directreward_ratio"));
		double ratio = type == WdyDirectReward.RECHARGE ? rechargeRatio.doubleValue() : buyProductRatio.doubleValue();
		BigDecimal rewardAmount = BigDecimalUtil.getP2BigDecimal(BigDecimalUtil.multiply(txnAmount, ratio));

		if(rewardAmount.compareTo(BigDecimal.ZERO) > 0) {
			WdyUser updateUser = new WdyUser();
			updateUser.setCnnWithdrawAmount(BigDecimalUtil.add(referrerUser.getCnnWithdrawAmount(), rewardAmount));
			updateUser.setVersion(referrerUser.getVersion());
			if(!wdyUserService.update(updateUser, referrerQuery)) {
				throw new BusinessException(ResultConstants.FI2007, "系统繁忙，请稍后重试");
			}
			WdyDirectReward directReward = new WdyDirectReward();
			directReward.setUserId(referrerId);
			directReward.setRewardType(type);
			directReward.setGrantTime(new Date());
			directReward.setGrantStatus(BaseEntity.YES);
			directReward.setRewardAmount(rewardAmount);
			directReward.setCreateBy(userId);
			this.save(directReward);

			WdyTxnHistory txnHistory = new WdyTxnHistory();
			txnHistory.setUserId(referrerId);
			txnHistory.setTxnId(String.valueOf(directReward.getId()));
			txnHistory.setTxnAmount(rewardAmount);
			txnHistory.setTxnType(TxnType.DIRECT_REWARD.getCode());
			txnHistory.setAmountType(TxnType.DIRECT_REWARD.getAmountType().getCode());
			String typeStr = type == WdyDirectReward.RECHARGE ? "充值" : "理财";
			txnHistory.setTxnDesc(typeStr + TxnType.DIRECT_REWARD.getName());
			wdyTxnHistoryService.save(txnHistory);
		}

		if(type == WdyDirectReward.BUY_PRODUCT) {
			wdyBuyProductService.incrReleaseAmount(referrerId);
		}
	}
}
